/*
 * Copyright (c) 2001, 2002 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */

#include "StdAfx.h"

JNIEXPORT void JNICALL Java_net_sourceforge_perforce_api_internal_SpecData_construct(JNIEnv* env, jobject javaSpecData)
{
	setNativeHandle(env, javaSpecData, new SpecDataTable());
}

JNIEXPORT void JNICALL Java_net_sourceforge_perforce_api_internal_SpecData_destruct(JNIEnv* env, jobject javaSpecData)
{
	SpecDataTable* specData = (SpecDataTable*)getNativeHandle(env, javaSpecData);
		
	delete specData;
	setNativeHandle(env, javaSpecData, NULL);
}

JNIEXPORT jobject JNICALL Java_net_sourceforge_perforce_api_internal_SpecData_getSpecDataMap(JNIEnv* env, jobject javaSpecData)
{
	if (env->ExceptionOccurred())
		return NULL;

	jclass clazz = env->FindClass("java/util/HashMap");
	jmethodID constructor = env->GetMethodID(clazz, "<init>", "()V");
	jobject propertyMap = env->NewObject(clazz, constructor);

	jmethodID putMethod = env->GetMethodID(clazz, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");


	SpecDataTable* specData = (SpecDataTable*)getNativeHandle(env, javaSpecData);
	StrDict* varList = specData->Dict();

	StrRef key;
	StrRef value;

	int i = 0;
	while (varList->GetVar(i, key, value) != 0)
	{		
		jstring keyString = env->NewStringUTF(key.Text());
		jstring valueString = env->NewStringUTF(value.Text());

		env->CallObjectMethod(propertyMap, putMethod, keyString, valueString);

		i++;
	}

	return propertyMap;
}

JNIEXPORT jstring JNICALL Java_net_sourceforge_perforce_api_internal_SpecData_get(JNIEnv* env, jobject javaSpecData, jstring javaKey)
{
	if (env->ExceptionOccurred())
		return NULL;

	SpecDataTable* specData = (SpecDataTable*)getNativeHandle(env, javaSpecData);

	const char* key = env->GetStringUTFChars(javaKey, JNI_FALSE);
		
	StrPtr* value = specData->Dict()->GetVar(key);
	if (value == NULL)
		return env->NewStringUTF("");
	else
		return env->NewStringUTF(value->Text());
}

JNIEXPORT void JNICALL Java_net_sourceforge_perforce_api_internal_SpecData_replace(JNIEnv* env, jobject javaSpecData, jstring javaKey, jstring javaValue)
{
	if (env->ExceptionOccurred())
		return;

	SpecDataTable* specData = (SpecDataTable*)getNativeHandle(env, javaSpecData);

	const char* key = env->GetStringUTFChars(javaKey, JNI_FALSE);
	const char* value = env->GetStringUTFChars(javaValue, JNI_FALSE);

	specData->Dict()->ReplaceVar(key, value);
}
